package com.hbnu.dao;

import com.hbnu.entity.Word;
import com.hbnu.util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class WordDAO {
    // 按字母模糊查询单词
    public List<Word> searchWordByLetter(String letter) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Word> wordList = new ArrayList<>();

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM word WHERE word LIKE ? ORDER BY word LIMIT 20";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "%" + letter.toLowerCase() + "%");

            rs = pstmt.executeQuery();
            while (rs.next()) {
                Word word = new Word();
                word.setId(rs.getInt("id"));
                word.setWord(rs.getString("word"));
                word.setPhonetic(rs.getString("phonetic"));
                word.setDefinition(rs.getString("definition"));
                word.setExample(rs.getString("example"));
                wordList.add(word);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null){
                    rs.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (pstmt != null){
                    pstmt.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return wordList;
    }

    // 根据ID查询单词
    public Word getWordById(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Word word = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM word WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                word = new Word();
                word.setId(rs.getInt("id"));
                word.setWord(rs.getString("word"));
                word.setPhonetic(rs.getString("phonetic"));
                word.setDefinition(rs.getString("definition"));
                word.setExample(rs.getString("example"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return word;
    }
}